package com.bill99.rpc.reference.hessian;

import java.net.MalformedURLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bill99.rpc.common.util.UrlUtils;
import com.bill99.rpc.registry.url.ServiceUrl;
import com.caucho.hessian.client.HessianProxyFactory;

/**
 * @author sheng.zhang
 */
public class HessianProxyPool {

	private Logger logger = LoggerFactory.getLogger(getClass());

	private HessianProxyFactory proxyFactory = new HessianProxyFactory();

	private Map<String, Object> proxyMap = new ConcurrentHashMap<String, Object>();

	private static HessianProxyPool pool = null;

	private HessianProxyPool() {
	}

	public static final HessianProxyPool getPool() {
		if (pool == null) {
			pool = new HessianProxyPool();
		}
		return pool;
	}

	protected Object createProxy(Class<?> api, String url)
			throws MalformedURLException {
		return proxyFactory.create(api, url);
	}

	/**
	 * 
	 * @return
	 */
	public Object getProxy(ServiceUrl serviceUrl) {
		String serviceString = serviceUrl.toString();
		Object proxy = proxyMap.get(serviceString);
		if (proxy == null) {
			String hessianUrl = UrlUtils.buildHessianUrl(serviceUrl);
			try {
				Class<?> serviceInterface = Class.forName(serviceUrl
						.getServiceInterface());
				proxy = createProxy(serviceInterface, hessianUrl);
			} catch (MalformedURLException e) {
				logger.error(e.getMessage(), e);
			} catch (ClassNotFoundException e) {
				logger.error(e.getMessage(), e);
			}
			proxyMap.put(serviceString, proxy);
		}
		return proxy;
	}

	public boolean isEmpty() {
		return proxyMap.isEmpty();
	}
}
